import _ from 'lodash';
import Moment from 'moment';
export default {
  setSession(key, value) { // 数据保存到sessionStorage
    if (value === undefined || key === undefined) {
      return;
    }
    if (typeof value === 'number' || typeof value === 'string') {
      sessionStorage[key] = value;
    } else if (typeof value === 'object' && value !== null) {
      sessionStorage[key] = JSON.stringify(value);
    }
  },
  getSession(key) { // 获取sessionStorage数据
    if (!sessionStorage[key]) {
      return;
    }
    let value = sessionStorage[key];
    if (value.includes('[') || value.includes('{')) {
      value = JSON.parse(sessionStorage[key]);
    }
    return value;
  },
  deepClone(obj) { // 对象数组深拷贝方法
    return obj && JSON.parse(JSON.stringify(obj));
  },
  trim(s) { // 去掉前后空格
    return s.replace(/^\s+|\s+$/gm, '');
  },
  setCookie(name, value, expiremMinutes) {
    let exdate = new Date();
    exdate.setTime(exdate.getTime() + expiremMinutes * 60 * 1000);
    document.cookie = name + '=' + escape(value) + ((expiremMinutes == null) ? '' : ';expires=' + exdate.toGMTString());
  },
  getCookie(name) {
    if (document.cookie.length) {
      let cStart = document.cookie.indexOf(name + '=');
      if (cStart !== -1) {
        cStart = cStart + name.length + 1;
        let cEnd = document.cookie.indexOf(';', cStart);
        if (cEnd === -1) {
          cEnd = document.cookie.length;
        }
        return unescape(document.cookie.substring(cStart, cEnd));
      }
    }
    return '';
  },
  delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = this.getCookie(name);
    if (cval != null) {
      document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString();
    }
  },
  /** 指标图表数据处理方法 */
  dealLinesData(data, keyMap, toFixed) {
    let xAxis = [];
    toFixed = toFixed || 0;
    let seriesData = [];
    data.map(o => {
      if (!xAxis.includes(o.dt)) {
        xAxis.push(o.dt);
      }
      let val = o.value || o.value === 0 ? (Number(o.value)).toFixed(toFixed) : '';
      if (!keyMap[o.indexId].obj) {
        keyMap[o.indexId].obj = {};
        keyMap[o.indexId].data = [];
      }
      keyMap[o.indexId].obj[o.dt] = val;
    });
    xAxis.sort((a, b) => {
      return Moment(a).valueOf() - Moment(b).valueOf();
    });
    xAxis.map(dt => {
      /**
       * 所有id遍历
       * 目的：补齐没有日期的id数据
       */
      for (let id in keyMap) {
        let o = keyMap[id];
        if (o.obj) {
          keyMap[id].data.push(o.obj[dt] || '');
        }
      }
    });
    for (let id in keyMap) {
      let o = keyMap[id];
      seriesData.push({
        name: o.name,
        data: o.data || [],
        yIndex: o.yIndex || 0
      });
    }
    return {
      xAxis,
      seriesData
    };
  },
  /** 指标饼图数据处理方法
   *  @param {String} config.indexId 唯一id：用来循环判断相加
   *  @param {String} config.value key值：（例'pigSaleWeight'）
  */
  dealPieData(data, config = {}) {
    let arr = [];
    let name = config.name || 'indexName';
    let value = config.value || 'value';
    data.map(o => {
      let index = _.findIndex(arr, (i) => {
        return o[`${name}`] === i.name;
      });
      if (index >= 0) {
        arr[index].value = Number(arr[index].value) + Number(o[`${value}`]);
      } else {
        arr.push({
          name: o[`${name}`],
          indexId: o.indexId,
          value: o[`${value}`]
        });
      }
    });
    return arr;
  },
  /** 雷达数据处理方法 */
  dealRadarData(data) {
    let seriesData = [];
    data.map(o => {
      seriesData.push(o.value);
    });
    return {
      seriesData: seriesData
    };
  },
  /** 处理排行榜数据 */
  dealRankData(data, config = {}) {
    let value = config.value || 'value';
    let name = config.name || 'indexName';
    let xAxis = [];
    let seriesData = [];
    data.map(o => {
      xAxis.push(o[`${name}`]);
      seriesData.push(o[`${value}`]);
    });
    return {
      xAxis,
      seriesData
    };
  },
  /**
   * 处理仪表盘数据
   * @param data 指标接口返回数据
   * @param text 仪表盘中间显示文本
   * @param numerator 仪表盘百分比取值 分子对于indexId
   * @param denominator 仪表盘百分比取值 分母对于indexId
   */
  dealGaugeData(data, text, numerator, denominator, config = {}) {
    let seriesData = [];
    let obj = {}
    data.forEach(item => {
      obj[item['indexId']] = item['value']
    });
    let val = '--';
    if ((Number(obj[numerator]) || Number(obj[numerator]) === 0) && Number(obj[denominator])) {
      val = Math.round(Number(obj[numerator]) / Number(obj[denominator]) * 10000)/100 || 0;
    }
    seriesData = [
      {
        name: text, value: val
      }
    ]
    let clientWidth = document.documentElement.clientWidth;
    let w = (clientWidth / 1280) * 100 * 0.1;
    let detail = {
      fontSize: w * 1.6,
      lineHeight: w * 1.6,
      formatter: '{value}%',
      offsetCenter: [0, -8],
    }
    let titleSet = { show: true, fontSize: w * 0.9,offsetCenter: [0, 15], }
    return {
      seriesData,
      detail,
      titleSet,
      obj
    }
  },
  isMobile() {
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    return flag;
  },
  /** 获取地址栏参数 */
  getUrlArgument(name) {
    var reg = new RegExp( "(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.href.substr(1).match(reg);
    if (r!= null ) return unescape(r[2]); return null;
  },
  /** 修改地址栏参数 */
  changeURLStatic(name, value){
    let url = changeURLParam(location.href, name, value); // 修改 URL 参数
    history.replaceState(null, null, url);  // 替换地址栏
    function changeURLParam(url, name, value) {
      if (typeof value === 'string') {
        value = value.toString().replace(/(^\s*)|(\s*$)/, ""); // 移除首尾空格
      }
      let url2;
      if (!value) { // remove
        let reg = eval('/(([\?|&])' + name + '=[^&]*)(&)?/i');
        let res = url.match(reg);
        if (res) {
          if (res[2] && res[2] === '?') { // before has ?
            if (res[3]) { // after has &
              url2 = url.replace(reg, '?');
            } else {
              url2 = url.replace(reg, '');
            }
          } else {
            url2 = url.replace(reg, '$3');
          }
        }
      } else {
        let reg = eval('/([\?|&]' + name + '=)[^&]*/i');
        if (url.match(reg)) { // edit
          url2 = url.replace(reg, '$1' + value);
        } else { // add
          let reg = /([?](\w+=?)?)[^&]*/i;
          let res = url.match(reg);
          url2 = url;
          if (res) {
            if (res[0] !== '?') {
              url2 += '&';
            }
          } else {
            url2 += '?';
          }
          url2 += name + '=' + value;
        }
      }
      return url2;
    }
  },
};
